package com.sxwl.auth.service;

import com.sxwl.common.utils.NumberUtils;
import com.sxwl.mapper.UserMapper;
import com.sxwl.pojo.User;
import com.sxwl.utils.PasswordUtils;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author reading
 * @Description TODO
 * @Date 2020/4/2 20:41
 */
@Service
@Slf4j
public class UserService {
    private final String KEY_PREFIX = "user:verify:";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MailService mailService;
    @Autowired
    private UserMapper userMapper;

    public Boolean register(User user, String code) {
        String key = KEY_PREFIX + user.getEmail();
        String CacheEmail = stringRedisTemplate.opsForValue().get(key);
        //校验验证码
        if (!code.equals(CacheEmail)) {
            //不正确
            return false;
        }
        user.setCreated(new Date());
        // 生成盐
        String salt = PasswordUtils.salt();
        user.setSalt(salt);
        // 对密码进行加密
        user.setPassword(PasswordUtils.toMd5(user.getPassword(), salt));
        // 写入数据库
        boolean bool = this.userMapper.insertSelective(user) == 1;
        // 如果注册成功，删除redis中的code
        if (bool) {
            try {
                this.stringRedisTemplate.delete(key);
            } catch (Exception e) {
                log.error("删除缓存验证码失败，code：{}", code, e);
            }
        }
        return bool;
    }

    public Boolean sendVerifyCode(String email) {
        // 生成验证码
        String code = NumberUtils.generateCode(6);
        System.out.println("验证码"+code);
        try {
            // 将email存入redis
            this.stringRedisTemplate.opsForValue().set(KEY_PREFIX + email, code, 5, TimeUnit.MINUTES);
            // 发送短信
            Map<String, String> msg = new HashMap<>();
            msg.put("to", email);
            msg.put("code", code);
            //发送邮箱
            mailService.setJavaMailSender(msg);
            return true;
        } catch (Exception e) {
            log.error("发送验证码失败 e:{} email：{}， code：{}", email, code,e);
            return false;
        }

    }
    public Boolean checkData(String data) {
        User record = new User();
        record.setEmail(data);
        return this.userMapper.selectCount(record) == 0;
    }

    public User queryUser(String email, String password) {
        // 查询
        /**
         * User.builder() 等同于 User user=new User
         */
        User user = this.userMapper.selectOne(User.builder().email(email).build());
        // 校验用户名
        if (user == null) {
            return null;
        }
        // 校验密码
        if (!user.getPassword().equals(PasswordUtils.toMd5(password, user.getSalt()))) {
            return null;
        }
        // 用户名密码都正确
        return user;
    }

    public User getByidUserInfo(String uid) {
        User user = this.userMapper.selectOne(User.builder().id(Integer.valueOf(uid)).build());
        if(user!=null){
            user.setStrSex(user.getSex()==0?"女":"男");
        }
        return user;
    }
    public int updateUser(User user) {
        int i = this.userMapper.updateByPrimaryKeySelective(user);
            return  i;
    }
}
